//
//  WBNewFeatureView.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/7.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit

/// 新特性视图
class WBNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterButton: UIButton!
    
    @IBOutlet weak var pageCtrl: UIPageControl!
    
    
    //进入微博
    @IBAction func enterStatus(_ sender: Any) {
        removeFromSuperview()
    }
    
    class func newFeatureView() -> WBNewFeatureView {
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        v.frame = UIScreen.main.bounds
        //从xib加载的视图大小默认是600x600
        return v
    }
    override func awakeFromNib() {
        //如果使用自动布局页面，从xib加载默值大小是600x600
//        print(bounds)
        //添加四个图像
        let count = 4
        let rect = UIScreen.main.bounds
        
        for i in 0..<4 {
            let imageName = "new_feature_\(i + 1)"
            
            let imgView = UIImageView(image: UIImage(named: imageName))
            imgView.frame = rect.offsetBy(dx: rect.width * CGFloat(i), dy: 0)
            scrollView.addSubview(imgView)
        }
        scrollView.contentSize = CGSize(width: rect.width * CGFloat(count + 1), height: rect.height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        //隐藏按钮
        enterButton.isHidden = true
        scrollView.delegate = self
//        print(scrollView.subviews.count)
        //禁止分页控件可点击事件
//        self.pageCtrl.isUserInteractionEnabled = false
    }
}

extension WBNewFeatureView:UIScrollViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let subViewsCount = scrollView.subviews.count
        //滚动到最后一屏，让视图删除
        let pageCount = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        //判断是否是最后一页
        if pageCount == subViewsCount {
            removeFromSuperview()
        }
        enterButton.isHidden = (pageCount != (subViewsCount - 1))
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //一旦滚动就隐藏按钮
        enterButton.isHidden = true
        //计算当前的偏移量
        let pageCount = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        //设置分页控件
        pageCtrl.currentPage = pageCount
        //分页控件的隐藏
        pageCtrl.isHidden = (pageCount == scrollView.subviews.count)
    }
}
